package com.xhs.exception;

import com.xhs.message.Result;
import com.xhs.message.ReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Arrays;
import java.util.Set;

/**
 * @desc: 全局异常拦截
 * @projectName: spring-boot-redis
 * @author: xhs
 * @date: 2024-06-21 021 15:00
 * @version: JDK 1.8
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * 参数校验的异常(post)
     *
     * @param ex 异常
     * @return Object
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnResult<Object> methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("参数校验失败(POST):", ex);
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.error("参数校验失败(POST):{}", fieldError.getDefaultMessage());
        return ReturnResult.error(400, fieldError.getDefaultMessage());
    }

    /**
     * 参数校验的异常(get)
     *
     * @param ex 异常
     * @return Object
     */
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public ReturnResult<Object> constraintViolationException(ConstraintViolationException ex) {
        log.error("参数校验失败(GET):", ex);
        StringBuilder errorInfo = new StringBuilder();
        String errorMessage;
        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {
            errorInfo.append(item.getMessage()).append(",");
        }
        errorMessage = errorInfo.substring(0, errorInfo.toString().length() - 1);
        return ReturnResult.error(400, errorMessage);
    }

    /**
     * 全局异常拦截（拦截项目中的所有异常）
     *
     * @param e 异常
     * @return ReturnResult
     */
    @ResponseBody
    @ExceptionHandler
    public ReturnResult<Object> handlerException(Exception e) {
        // 如果是通用业务异常，直接返回给前端
        if (e instanceof CommonException) {
            CommonException ee = (CommonException) e;
            log.error("通用业务异常:", ee);
            return ReturnResult.error(ee.getCode(), ee.getMsg());
        } else if (e instanceof MultipartException) {
            MultipartException ee = (MultipartException) e;
            log.error("Multipart请求异常:", ee);
            return ReturnResult.error(Result.PARAMS_ERROR.getCode(), "请求格式错误：必须为 multipart/form-data 类型 " + ee.getMessage());
        } else if (e instanceof MissingServletRequestPartException) {
            MissingServletRequestPartException ex = (MissingServletRequestPartException) e;
            log.error("Multipart请求异常:", ex);
            return ReturnResult.error(Result.PARAMS_ERROR.getCode(), "必需的文件字段缺失或字段名不匹配 " + ex.getMessage());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            HttpRequestMethodNotSupportedException ex = (HttpRequestMethodNotSupportedException) e;
            String errorMsg = String.format("请求方法不支持：应为 %s，实际为 %s", Arrays.toString(ex.getSupportedMethods()), ex.getMethod());
            log.error("请求方法不支持异常:", ex);
            return ReturnResult.error(Result.PARAMS_ERROR.getCode(), errorMsg);
        } else {
            log.error("全局异常:", e);
            return ReturnResult.error();
        }
    }
}
